package cqu.zhaiyixin20215521.huarondao.slice.pintuInitialize;

import ohos.media.image.PixelMap;

import java.util.Arrays;

public class Pintu {
    private final Piece[] pieces;
    public final int rowNum;
    public final int colNum;
    private int count;

    public static class Piece {
        public int number;
        public PixelMap pixelMap;

        public Piece(int number, PixelMap pixelMap) {
            this.number = number;
            this.pixelMap = pixelMap;
        }
    }

    public Pintu(int rowNum, int colNum) {
        this.rowNum = rowNum;
        this.colNum = colNum;
        this.pieces = new Piece[rowNum * colNum];
    }

    //插入拼图
    public boolean insert(Pintu.Piece piece, int index) {
        if(0 <= index && index < pieces.length && pieces[index] == null) {
            pieces[index] = piece;
            count++;
            return true;
        } else {
            return false;
        }
    }

    public boolean insert(Piece piece, int row, int col) {
        if(0 <= row && row < rowNum && 0 <= col && col < colNum) {
            return insert(piece, row * colNum + col);
        } else {
            return false;
        }
    }

    //移除拼图
    public Piece remove(int index) {
        if(0 <= index && index < pieces.length && pieces[index] != null) {
            Piece piece = pieces[index];
            pieces[index] = null;
            count--;
            return piece;
        } else {
            return null;
        }
    }

    public Piece remove(int row, int col) {
        if(0 <= row && row < rowNum && 0 <= col && col < colNum) {
            return remove(row * colNum + col);
        } else {
            return null;
        }
    }

    public Piece removeIfEquals(int index, Piece piece) {
        if(0 <= index && index < pieces.length && pieces[index] != null && pieces[index].equals(piece)) {
            return remove(index);
        } else {
            return null;
        }
    }

    public Piece removeIfEquals(int row, int col, Piece piece) {
        if(0 <= row && row < rowNum && 0 <= col && col < colNum) {
            return removeIfEquals(row * colNum + col, piece);
        } else {
            return null;
        }
    }

    //当前拼图有多少小方块
    public int getCount() {
        return count;
    }

    public int size() {
        return rowNum * colNum;
    }

    public Piece get(int row, int col) {
        if(0 <= row && row < rowNum && 0 <= col && col < colNum) {
            return pieces[row * colNum + col];
        } else {
            return null;
        }
    }

    public Piece get(int index) {
        if(0 <= index && index < size()) {
            return pieces[index];
        } else {
            return null;
        }
    }

    public void clearAll() {
        Arrays.fill(pieces, null);
        count = 0;
    }

}
